{% extends 'base.html' %}

{% block javascript %}
<script>

  window.onload = function() {
    getInfoAndUpdateView()
  }

  function getInfoAndUpdateView() {
    console.log("Getting info and updating view")

    // Initialize status and view
    document.getElementById("status").innerHTML = "Loading network status..."
    $('#danger-zone-collapse').collapse("hide");



    // Initialize info vars
    var systemInfo = {};
    var networkInfo = {};
    var iotInfo = {};

    // Get system info
    getSystemInfo()
      .then(function(systemInfo) {
        var systemInfo = systemInfo;
        
        // Get network info
        getNetworkInfo()
          .then(function(networkInfo) {
            var networkInfo = networkInfo;

            // Get iot info
            getIotInfo()
              .then(function(iotInfo) {
                var iotInfo = iotInfo;

                // Update view
                updateView(systemInfo, networkInfo, iotInfo)
              })
          })
      })
      .catch(function(error) {
        console.log("Error: " + error);
      })
  }

  function updateView(systemInfo, networkInfo, iotInfo) {
    console.log("Updating view");
    console.log(systemInfo)
    console.log(networkInfo)
    console.log(iotInfo)

// Update view for connected network and connected iot
    if (networkInfo["isConnected"] && iotInfo["isConnected"]) {
      document.getElementById("status").innerHTML = "Successfully connected!"
      document.getElementById("ip-address").innerHTML = networkInfo["ipAddress"];
      document.getElementById("remote-device-ui-url").innerHTML = systemInfo["remoteDeviceUiUrl"];
      document.getElementById("remote-device-ui-url").href = systemInfo["remoteDeviceUiUrl"];
      document.getElementById("cloud-ui-url").innerHTML = "https://openag-v1.appspot.com/login/";
      document.getElementById("cloud-ui-url").href = "https://openag-v1.appspot.com/login/";
      $('#connection-info-collapse').collapse("show");
      $('#configure-wifi-collapse').collapse("hide");
      $('#danger-zone-collapse').collapse("show");
    }

    // Update view for connected network and unconnected iot
    else if (networkInfo["isConnected"] && !iotInfo["isConnected"]) {
      document.getElementById("status").innerHTML = "Connected to network, disconnected from iot"
      document.getElementById("ip-address").innerHTML = networkInfo["ipAddress"];
      document.getElementById("remote-device-ui-url").innerHTML = systemInfo["remoteDeviceUiUrl"];
      document.getElementById("remote-device-ui-url").href = systemInfo["remoteDeviceUiUrl"];
      document.getElementById("cloud-ui-url").innerHTML = "Please click here to create your user account, and connect your PFC to the OpenAg Cloud";
      document.getElementById("cloud-ui-url").href = "https://openag-v1.appspot.com/login?vcode=" + iotInfo["verificationCode"];
      $('#connection-info-collapse').collapse("show");
      $('#configure-wifi-collapse').collapse("hide");
      $('#danger-zone-collapse').collapse("show");
    }

    // Update view for disconnected network and non-wifi-enabled system
    else if (!networkInfo["isConnected"] && !systemInfo["isWifiEnabled"]) {
        document.getElementById("status").innerHTML = "Unable to connect, not a wifi enabled"
        $("#configure-wifi-collapse").collapse("hide");
        $("#connection-info-collapse").collapse("hide");
    }

    // Update view for disconnected network and wifi-enabled system
    else if (!networkInfo["isConnected"] && systemInfo["isWifiEnabled"]) {
      document.getElementById("status").innerHTML = "Please configure your wifi network"
      updateWifiAccessPoints(networkInfo["wifiAccessPoints"])
      $("#configure-wifi-collapse").collapse("show");
      $("#network-info-collapse").collapse("hide");
    }
  }


  function updateWifiAccessPoints(wifiAccessPoints) {
    console.log("Updating wifi access points")

    // Get wifi access point select
    var wifiAccessPointSelect = document.getElementById("wifi-access-points-select");

    // Remove stale wifi access point selections
    if (wifiAccessPointSelect != null) {
      for( i=wifiAccessPointSelect.length - 1; i >= 0; i-- ) { // must do in reverse
        wifiAccessPointSelect.remove(i);
      } 
    }

    // Add updated wifi access point selections
    if (wifiAccessPoints != null) {
      for( i=0; i < wifiAccessPoints.length; i++ ) {
        wifiAccessPoint = wifiAccessPoints[i];
        var option = document.createElement("option");
        option.text = wifiAccessPoint.ssid;
        option.value = wifiAccessPoint.psk;
        wifiAccessPointSelect.add(option);
      }
    }
  }

  function getSystemInfo() {
    console.log("Getting system info")
    return new Promise(function (resolve, reject) {
      $.ajax({
        url: "/api/system/info/",
        type: "GET",
        data: {
          "csrfmiddlewaretoken": "{{ csrf_token }}"
        },
        dataType: 'json',
        success: function(data) {
          console.log("Got system info")
          var systemInfo = {
            "platform": data["platform"],
            "isWifiEnabled": data["is_wifi_enabled"],
            "serialNumber": data["serial_number"],
            "remoteDeviceUiUrl": data["remote_device_ui_url"]
          };
          resolve(systemInfo);
        },
        error: function(data) {
          response_dict = JSON.parse(data.responseText);
          message = response_dict["message"];
          console.log(message);
          var systemInfo = {};
          reject(systemInfo);
        }
      });
    });
  }

  function getNetworkInfo() {
    console.log("Getting network info")
    return new Promise(function (resolve, reject) {
      $.ajax({
        url: "/api/network/info/",
        type: "GET",
        data: {
          "csrfmiddlewaretoken": "{{ csrf_token }}"
        },
        dataType: 'json',
        success: function(data) {
          console.log("Got network info")
          var networkInfo = {
            "isConnected": data["is_connected"],
            "ipAddress": data["ip_address"],
            "wifiAccessPoints": data["wifi_access_points"]
          }
          resolve(networkInfo);
        },
        error: function(data) {
          console.log("Unable to get network info")
          response_dict = JSON.parse(data.responseText)
          message = response_dict["message"]
          console.log(message);
          var networkInfo = {};
          reject(networkInfo);
        }
      });
    });
  }

  function getIotInfo() {
    console.log("Getting iot info")
    return new Promise(function (resolve, reject) {
      $.ajax({
        url: "/api/iot/info/",
        type: "GET",
        data: {
          "csrfmiddlewaretoken": "{{ csrf_token }}"
        },
        dataType: 'json',
        success: function(data) {
          console.log("Got system info")
          var iotInfo = {
            "isRegistered": data["is_registered"],
            "isConnected": data["is_connected"],
            "verificationCode": data["verification_code"]
          };
          resolve(iotInfo);
        },
        error: function(data) {
          response_dict = JSON.parse(data.responseText);
          message = response_dict["message"];
          console.log(message);
          var iotInfo = {};
          reject(iotInfo);
        }
      });
    });
  }

  function joinWifiAdvanced() {
    console.log("Joining wifi advanced")
    
    // Update status and processing view
    document.getElementById("status").innerHTML = "Joining wifi, this will take a few minutes..."
    $('#configure-wifi-collapse').collapse("hide");

    // Get advanced wifi parameters
    var SSIDName = document.getElementById("ssid-name").value;
    var passphrase = document.getElementById("wifi-passphrase").value;
    var hiddenSSID = document.getElementById("hidden-ssid").value;
    var security = document.getElementById("security").value;
    var eap = document.getElementById("eap").value;
    var identity = document.getElementById("identity").value;
    var phase2 = document.getElementById("phase2").value;

    // TODO: Validate parameters

    // Send join wifi request
    console.log("Sending join wifi request");
    $.ajax({
      url: "/api/network/joinwifiadvanced/",
      type: "POST",
      data: {
        "csrfmiddlewaretoken": "{{ csrf_token }}",
        "ssid_name": SSIDName,
        "passphrase": passphrase,
        "hidden_ssid": hiddenSSID,
        "security": security,
        "eap": eap,
        "identity": identity,
        "phase2": phase2,
      },
      dataType: 'json',
      success: function(data) {
        console.log("Successfully joined wifi advanced");
        getInfoAndUpdateView();
      },
      error: function(data) {
        console.log("Unable to join wifi advanced");
        response_dict = JSON.parse(data.responseText);
        message = response_dict["message"];
        console.log(message);
        console.log(response_dict);
        getInfoAndUpdateView();
      }
    });
  }

  function deleteWifis() {
    console.log("Deleting wifi")
    
    // Update status & processing view
    document.getElementById("status").innerHTML = "Deleting wifis, this will take a few minutes..."
    $('#connection-info-collapse').collapse("hide");
    $('#danger-zone-collapse').collapse("hide");

    // Send join wifi request
    console.log("Sending delete wifis request");
    $.ajax({
      url: "/api/network/deletewifis/",
      type: "POST",
      data: {
        "csrfmiddlewaretoken": "{{ csrf_token }}",
      },
      dataType: 'json',
      success: function(data) {
        console.log("Successfully deleted wifis");
        getInfoAndUpdateView();
      },
      error: function(data) {
        console.log("Unable to delete wifis");
        response_dict = JSON.parse(data.responseText);
        message = response_dict["message"];
        console.log(message);
        console.log(response_dict);
        location.reload(true);
        // getInfoAndUpdateView();
      }
    });
  }

  function reregisterIot() {
    console.log("Re-registering w/iot")
    
    // Update status
    document.getElementById("status").innerHTML = "Re-registering iot, this will take a few minutes..."

    // Send join wifi request
    console.log("Sending re-register iot request");
    $.ajax({
      url: "/api/iot/reregister/",
      type: "POST",
      data: {
        "csrfmiddlewaretoken": "{{ csrf_token }}",
      },
      dataType: 'json',
      success: function(data) {
        console.log("Successfully re-registered w/iot");
        location.reload();
      },
      error: function(data) {
        console.log("Unable to re-register w/iot");
        response_dict = JSON.parse(data.responseText);
        message = response_dict["message"];
        console.log(message);
        console.log(response_dict);
        location.reload();
      }
    });
  }

  function makePasswordVisible() {
    var pass = document.getElementById("wifi-passphrase");
    if (pass.type === "password") {
        pass.type = "text";
    } else {
        pass.type = "password";
    }
  }


</script>
{% endblock %}


{% block content %}
<html>

<input type="hidden" id="wifi-access-points" name="variable", value="temp">

<body>

<div class="connect">
  
  <h2>Connect (Advanced)</h2>

    <!-- Networking Card -->
    <div class="card" id="connect-card">
      <h3>Networking</h3></br>
      <p> <b>Status:</b> <span id="status"></span></p>

      <ul>

      <!-- Connection Info Collapese -->
      <div class="collapse" id="connection-info-collapse">
        <li><b>Device IP Address:</b> <span id="ip-address"></span>
        <li><b>Web UI:</b> <a id="cloud-ui-url" href="https://openag-v1.appspot.com/login" target="_blank">OpenAg Web UI</a>
        <li><b>Remotely Accessible Device UI:</b> <a id="remote-device-ui-url" href="" target="_blank"></a>
      </div>
      
      <!-- Configure Wifi Collapse -->
      <div class="collapse" id="configure-wifi-collapse">
        <!-- Wifi Access Point Passphrase and Select -->
        <li>
          <div><b>Access Point Name:</b> (also called an SSID)</div>
          <input type="text" id="ssid-name" style="width:400px"
           autocomplete="new-password" placeholder="SSID">
          <select id="wifi-access-points-select" class="selectpicker" style="width:200px"
           onchange="document.getElementById('ssid-name').value=this.value">
            <option value=""></option>
            {% for wifi_access_point in wifi_access_points %}
            <option value="{{wifi_access_point.service}}">{{wifi_access_point.ssid}}</option>
            {% endfor %}
          </select>
        </li></br>

        <!-- Hidden SSID Select -->
        <li>
          <div><b>Hidden SSID:</b> (is the above SSID hidden?)</div>
          <select id="hidden-ssid" class="selectpicker" style="width:200px">
            <option value="false" selected="selected">False</option>
            <option value="true">True</option>
          </select>
        </li></br>

        <!-- Passphrase Entry -->
        <li>
          <div><b>Passphrase:</b> (or password)</div>
          <input type="password" id="wifi-passphrase" autocomplete="new-password"
           onkeydown="if (event.keyCode==13) document.getElementById('butJoin').click()"
           placeholder='Passphrase' style="width:200px">
          <input type="checkbox" onclick="makePasswordVisible()"> Show passphrase
        </li></br>

        <!-- Security Config -->
        <li>
          <div><b>Security:</b> (which security protocol do you use?)</div>
          <select id="security" class="selectpicker" style="width:200px"
           onchange="if( this.value == 'ieee8021x' ) {
              $('#eap-parameters-collapse').collapse('show');
             } else {
              $('#eap-parameters-collapse').collapse('hide');
             }">
            <option value="ieee8021x">WPA EAP</option>
            <option value="psk">WPA/WPA2 PSK</option>
            <option value="wep">WEP</option>
            <option value="none" selected="selected">None</option>
          </select>
        </li></br>

        <!-- EAP Parameters Collapse-->
        <div class="collapse" id="eap-parameters-collapse">
          <li>
            <div><b>EAP:</b> (which Extensible Authentication Protocol do you use?)</div>
            <select id="eap" class="selectpicker" style="width:200px">
              <option value="tls">TLS</option>
              <option value="ttls">TTLS</option>
              <option value="peap">PEAP</option>
            </select>
          </li></br>

          <li>
            <div><b>Identity:</b> (EAP identity string. Could be an email address, user name or other ID.)</div>
            <input type="text" id="identity" style="width:200px"
             autocomplete="new-password" placeholder="Identity">
          </li></br>

          <li>
            <div><b>Phase2:</b> (Inner EAP authentication type. Could be "MSCHAPV2")</div>
            <input type="text" id="phase2" style="width:200px"
             autocomplete="new-password" placeholder="Phase2">
          </li></br>
          
        </div>

        <!-- Join Wifi Button -->
        </li>
          <a class="badge badge-secondary" data-toggle="collapse" id="join-wifi-button"
          style="width:200px" href="" role="button" onclick="joinWifiAdvanced();">
          Join Wifi</a>
        </li>

      </ul>
      </div>


    <!-- Danger Zone Card -->
    <div class="collapse" id="danger-zone-collapse">
      <div class="card" id="connect-card">
        <h3>Danger Zone</h3><br/>
        <ul>
          <li><a class="badge badge-secondary" data-toggle="collapse"
           style="width:200px" href="" role="button" onclick="deleteWifis();">
           Delete Wifi Connections</a> <span id="delete-wifi-button"></span></li>
          <li><a class="badge badge-secondary" data-toggle="collapse"
           style="width:200px" href="" role="button" onclick="reregisterIot();">
           Re-Register Device</a> <span id="reregister-iot-button"></span></li>
        </ul>
      </div>
    </div>
  </div>
</div>
</body>
</html>
{% endblock %}
